<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Canvas</title>
    <style></style>
  </head>
  <body>
    <div class="container">
      <canvas id="demo"></canvas>
    </div>

    <script>
      ;(function () {
        const $canvas = document.querySelector('#demo')
        $canvas.width = 600
        $canvas.height = 600
        $canvas.style.border = '1px solid #cccccc'

        const context = $canvas.getContext('2d')

        function draw() {
          // 处理画布之前的绘制，不受影响
          context.fillRect(10, 10, 10, 10)

          // 保存当前 画布状态 到缓存
          context.save()

          // 把当前画布移动到 200，200
          context.translate(200, 200)
          //  旋转画布 30度
          context.rotate((Math.PI / 180) * 30)
          // x,y 方向放大两倍画布
          context.scale(2, 2)
          // 透明画布
          context.globalAlpha = 0.5

          context.moveTo(0, 0)
          context.lineTo(400, 0)
          context.moveTo(0, 0)

          context.lineTo(0, 400)

          context.stroke()
          context.fillRect(10, 10, 20, 20)

          // 把缓存中保存的状态恢复
          context.restore()
          context.fillStyle = 'red'
          context.fillRect(20, 20, 30, 30)
        }

        draw()
      })()
    </script>
  </body>
</html>
